package com.lagou.interceptor;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author tengfei wang
 * @version 1.0
 * @date Created in 2020/9/17
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    private static final String TOKEN_NAME = "token";
    private static final String TOKEN_VALUE = "ASDQ23EQ21313A";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length <= 0) {
            response.sendRedirect("/login");
            return false;
        }
        for (Cookie cookie : cookies) {
            if (TOKEN_NAME.equals(cookie.getName()) && TOKEN_VALUE.equals(cookie.getValue())) {
                return true;
            }
        }
        response.sendRedirect("/login");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }
}
